﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.AutoMap;
using System.Web;

namespace WorkOrders.Data
{
    static class SessionManager
    {
        private static ISessionFactory _sessionFactory;
        private static ISessionStrategy _strategy;

        public static ISessionStrategy Strategy
        {
            get
            {
                if (_strategy == null)
                {
                    if (HttpContext.Current == null) 
                        _strategy = new SingletonStrategy();
                    else
                        _strategy = new WebStrategy();
                }
                return _strategy;
            }
            set
            {
                _strategy = value;
            }
        }
        
        private static ISessionFactory SessionFactory<T>() where T : class
        {
            if (_sessionFactory == null)
            {
                var connString = ConfigurationManager.ConnectionStrings["WorkOrders"].ConnectionString;
                _sessionFactory = Fluently
                    .Configure()
                    .Database(MsSqlConfiguration
                                  .MsSql2005
                                  .ConnectionString(c => c
                                                             .Is(connString)))
                    .Mappings(m => 
                                  {
                                      m.FluentMappings.AddFromAssemblyOf<T>();
                                      m.AutoMappings.Add(AutoPersistenceModel
                                                             .MapEntitiesFromAssemblyOf<T>()
                                                             .Where(type => type.Namespace.EndsWith("Entities")));
                                  })
                    .BuildSessionFactory();
            }
            return _sessionFactory;
        }

        public static ISession GetSession<T>() where T : class
        {
            var currentSession = Strategy.FindSession();
            if (currentSession == null)
            {
                var sessionFactory = SessionFactory<T>();
                currentSession = sessionFactory.OpenSession();
                Strategy.AddSession(currentSession);
            }
            return currentSession;
        }

        public static void CloseSession()
        {
            var currentSession = Strategy.FindSession();
            if (currentSession != null)
            {
                currentSession.Clear();
                currentSession.Close();
                Strategy.RemoveSession();
            }
        }
    }
}